package hn.cch.grammar.io;

import org.junit.jupiter.api.Test;

import java.io.CharArrayReader;
import java.io.CharArrayWriter;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;

/**
 * 字符流
 */
public class ReaderWriterDemo {


    @Test
    public void testFile() {
        String content = "line1\nline2";
        StringBuilder ascii = new StringBuilder(127);
        for (int i = 0; i < 127; i++) {
            ascii.append((char) i);
        }

        StringBuilder stringBuilder = new StringBuilder();
        for (int i = 0; i < 1024; i++) {
            stringBuilder.append(ascii);
        }
        content = stringBuilder.toString();


        String dir = "src/main/resources/ReaderWriter";
        File file = new File(dir);

        char[] charArray = new char[1024];


        try (FileWriter fileWriter = new FileWriter(new File(file, "f1.txt"))) {
            fileWriter.write(content);
            fileWriter.flush();

            // BufferedWriter
            // BufferedWriter bufferedWriter = new BufferedWriter(fileWriter);
            // bufferedWriter.write(content);
            // bufferedWriter.flush();

            // PrintWriter
            // PrintWriter printWriter = new PrintWriter(fileWriter);
            // printWriter.write(content);
            // printWriter.flush();

        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
        int size = 0;
        try (FileReader fileReader = new FileReader(new File(file, "f1.txt"))) {
            CharArrayWriter charArrayWriter = new CharArrayWriter();
            while (-1 != (size = fileReader.read(charArray))) {
                charArrayWriter.write(charArray, 0, size);
            }
            System.out.println(String.valueOf(charArrayWriter.toCharArray()));
        } catch (IOException e) {
            System.out.println(e.getMessage());
        }
    }

    @Test
    public void testCharArray() {

        char[] charArray = new char[1024];
        CharArrayReader charArrayReader = new CharArrayReader(charArray);
        // charArrayReader.
    }
}
